/**
 * FriendsEmailAddressesDao.java
 * Copyright2011 PinMeal
 */
package com.pinmeal.persistent;

import java.util.Vector;

import com.pinmeal.constants.DaoNameConstants;
import com.pinmeal.types.FriendData;
import com.pinmeal.types.PinMealParsingException;
import com.pinmeal.types.PinMealType;

/**
 * @author albertma 
 * Jul 19, 2011
 */
public class FriendsEmailAddressesDao extends AbstractFileLineDao
{
    private static FriendsEmailAddressesDao instance = new FriendsEmailAddressesDao();
    
    private Vector<FriendData> friendsList;

    private String groupName;
    public static FriendsEmailAddressesDao getInstance()
    {
        return instance;
    }
    
    public void init()
    {
        //read the data from specific files.
        friendsList = new Vector<FriendData>();
        loadFromFile(DaoNameConstants.FRIENDS_EMAIL_NAME);
    }

    @Override
    protected void parseLineDelegate(String line) throws PinMealParsingException
    {
        int index = line.indexOf('$');
        if (index >= 0)
        {
            CharSequence groupName = line.subSequence(0, index);
           
            CharSequence groupDetail = line.subSequence(index + 1, line.length());
            int secondIndex = groupDetail.toString().indexOf('$');
            if (secondIndex >= 0)
            {
                CharSequence name = groupDetail.subSequence(0, index);
                CharSequence email = groupDetail.subSequence(secondIndex + 1, groupDetail.length());
                FriendData friendData = new FriendData();
                friendData.setName(name.toString());
                friendData.setEmail(email.toString());
                friendData.setGroup(groupName.toString());
                friendsList.add(friendData);
            }
            else
            {
                throw new PinMealParsingException();
            }
        }
        else
        {
            throw new PinMealParsingException();
        }
    }

    @Override
    protected String storeLineDelegate(PinMealType record)
    {
        String line = null;
        if(record instanceof FriendData)
        {
            line = groupName + '$' + ((FriendData) record).getName();
            line += "$" + ((FriendData) record).getEmail();
        }
        return line;
    }
    
    
    public boolean store(String groupName)
    {
        this.groupName = groupName;
        return this.storeToFile(friendsList, DaoNameConstants.FRIENDS_EMAIL_NAME);
    }
    
    public boolean add(FriendData data)
    {
        if(!this.friendsList.contains(data))
        {
           this.friendsList.add(data);
           return true;
        }
        return false;
    }
    
    public boolean remove(FriendData data)
    {
        return this.remove(data);
    }
    
    public int getSize()
    {
        return this.friendsList.size();
    }
    
    public FriendData get(int index)
    {
        return friendsList.get(index);
    }
}
